from django.db import DatabaseError
from rest_framework.response import Response
from rest_framework.views import exception_handler
from rest_framework import status
import logging

logger=logging.getLogger('django')
def costom_exception_handler(exc, context):
    '''自定义异常处理
    exc:异常类
    # context：抛出异常上下文
    （1）先调用导入的函数 exception_handler原生处理异常
    {

        如果response是空，说明有异常，然后再判断这个异常类的实例是不是我们自定义的异常
    }
    '''
    response = exception_handler(exc, context)
    if response is  None:
        view= context['view']
        if isinstance(exc,DatabaseError):
            logger.error('[%S] %s' % (view,exc))
            # 数据库异常
            response = Response({'message':'数据库异常'},status=status.HTTP_507_INSUFFICIENT_STORAGE)
            # 0不能为除数
        elif isinstance(exc,ZeroDivisionError):
            logger.error('[%s] %s' % (view, exc))
            response = Response({'message':'除数不能为0'},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    return response
